import React, { useState } from 'react';
import './WrjBack.less'
import {useDispatch,useSelector} from "react-redux"
import {addBackImg} from "../../../store/model/counter"

const Back: React.FC = () => {

  const dispatch=useDispatch()
  const [imageUrl,setImgageUrl]=useState('')

  const handleFileChange=(event:any)=>{
    const file = event.target.files[0];
    if (file) {
      const reader: FileReader = new FileReader();
      reader.onload =  () => {
        const img:HTMLImageElement = new Image();
        if(typeof reader.result==='string'){
          img.src = reader.result;
        }
        img.onload =  () => {
          const maxWidth = 300; // 设置最大宽度
          const maxHeight = 300; // 设置最大高度
          const imageWidth = img.width;
          const imageHeight = img.height;
          
          // 计算新的宽度和高度，以保持纵横比
          let newWidth=0 
          let newHeight=0
          if (imageWidth > imageHeight) {
              newWidth = maxWidth;
              newHeight = (imageHeight / imageWidth) * maxWidth;
          } else {
              newHeight = maxHeight;
              newWidth = (imageWidth / imageHeight) * maxHeight;
          }
          const canvas: HTMLCanvasElement = document.createElement('canvas');
          const ctx: CanvasRenderingContext2D | null = canvas.getContext('2d');
          canvas.width = newWidth;
          canvas.height = newHeight;
          ctx!.drawImage(img, 0, 0, newWidth, newHeight);
          
          // 将压缩后的图片转换为Base64数据URL
          const imgurl = canvas.toDataURL('image/jpeg', 0.2); // 可以调整压缩质量
          setImgageUrl(imgurl)
          // dispatch(addBackImg(imgurl.split(',')[1]))
          dispatch(addBackImg(imgurl))
        };
      }
      reader.readAsDataURL(file);
    }
  }

  return (
    <div className="wrj-back-file-input">
      {
        imageUrl==''?
        <input type="file" onChange={handleFileChange}/>:
        <img src={imageUrl} className="wrj-backImg" />
      }
  </div>
  );
};

export default Back;